package co.edu.uniandes.distribuidos.security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


/**
 * Clase para encriptar y descriptar vector de bytes
 *
 */
public class Cryptographic {
	
	public static final String ALGORITHM = "AES";
	public static final String TRANSFORMATION = "AES/ECB/NoPadding";
	
	private SecretKeySpec secretKeySpec;
	private Cipher cipher;
	/**
	 * Metodo constructor 
	 */
	public Cryptographic(String idPeer) {
		secretKeySpec = new SecretKeySpec(Key.getKey(idPeer), ALGORITHM);
	}
	/**
	 * Metodo para encriptar un vector de bytes
	 * @param input
	 * @return
	 * @throws Exception
	 */
	public byte[] encriptar(byte[] input) throws Exception{
		cipher = Cipher.getInstance(TRANSFORMATION);
		
        byte[] cipherText = new byte[input.length];
        
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
        
        ctLength += cipher.doFinal(cipherText, ctLength);
        
        return cipherText;
	}
	
	/**
	 * Metodo para desencriptar un vector de bytes
	 * @param cipherText
	 * @return
	 * @throws Exception
	 */
	public byte[] desencriptar(byte [] cipherText)throws Exception{
		cipher = Cipher.getInstance(TRANSFORMATION);
		int ctLength = cipherText.length;
		 byte[] plainText = new byte[ctLength];
	        
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

        int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
        
        ptLength += cipher.doFinal(plainText, ptLength);
        
        return plainText;
	}
	
}
